<template>
  <div class="board-container">
    <el-row :gutter="32">
      <el-form>
        <el-form-item label="视图名称" label-width="100">
          <el-col :xs="16" :sm="12" :md="8" :lg="8">
            <el-input
              v-model="boardForm.name"
              type="text"
              placeholder="请输入视图名"
            />
          </el-col>
          <el-col :xs="3" :sm="{span:'3',offset:'5'}" :md="{span:'2',offset:'10'}" :lg="{span:'2',offset:'10'}">
            <el-button type="primary" @click="addBoard">确定</el-button>
          </el-col>
        </el-form-item>
        <el-col :xs="12" :sm="12" :md="8" :lg="8">
          <el-select
            v-model="quotaIndex"
            style="width: 100%;"
            :loading="quotaLoading"
            placeholder="请选择指标"
            @change="handleQuotaChange"
          >
            <el-option
              v-for="item in quotaOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-col>
        <el-col :xs="12" :sm="12" :md="8" :lg="8">
          <el-select
            v-model="indexList"
            :disabled="disableDevice"
            style="width: 100%;"
            :multiple-limit="4"
            :loading="deviceLoading"
            multiple
            placeholder="请选择设备"
            @change="handleDeviceChange"
          >
            <el-option
              v-for="item in deviceOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-col>
      </el-form>
    </el-row>
    <el-row :gutter="32">
      <el-col :xs="24" :sm="24" :lg="24">
        <div class="chart-wrapper">
          <div align="center">指标数据预览</div>
          <line-chart ref="lineChart" />
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import resize from '@/components/Charts/mixins/resize'
import { addBoard, getDeviceByQuota, previewBoard, queryQuotaPage } from '@/api/board'
import { parseTime } from '@/utils'
import LineChart from '@/views/board/components/LineChart'

const defaultQuotaForm = { page: 1, pageSize: 10 }
const defaultDeviceForm = { quotaName: '', unit: '', page: 1, pageSize: 10 }

export default {
  name: 'CustomBoard',
  components: { LineChart },
  mixins: [resize],
  data() {
    return {
      loading: false,
      chart: null,
      quotaIndex: '',
      quotaLoading: true,
      disableDevice: true,
      indexList: '',
      deviceLoading: true,
      quotaForm: Object.assign({}, defaultQuotaForm),
      deviceForm: Object.assign({}, defaultDeviceForm),
      boardForm: { name: '', quotaName: '', unit: '', deviceIdList: '' },
      quotaOptions: [],
      deviceOptions: [],
      rules: {
        name: [{ required: true, message: '请输入视图名称', trigger: 'blur' }],
        quotaName: [{ required: true, message: '请输入指标名', trigger: 'blur' }],
        unit: [{ required: true, message: '请输入指标单位', trigger: 'blur' }],
        deviceIdList: [{ required: true, message: '请选择设备ID', trigger: 'blur' }]
      }
    }
  },
  created() {
    const data = { page: 1, pageSize: 10 }
    queryQuotaPage(data).then(resp => {
      const items = resp.data.pager.items
      this.quotaOptions = Array.from(items).map(item => ({
        value: items.indexOf(item),
        label: `${item.name}; 单位：${item.unit}`,
        name: item.name,
        unit: item.unit
      }))
      this.quotaLoading = false
    })
  },
  mounted() {
    this.$refs.lineChart.initChart()
  },
  methods: {
    addBoard() {
      if (isNaN(this.quotaIndex)) this.$message.error('参数错误')
      else if (this.boardForm.name === '') this.$message.error('缺少视图名称')
      else {
        if (this.boardForm &&
          this.boardForm.name && this.boardForm.unit &&
          this.boardForm.deviceIdList
        ) {
          addBoard(this.boardForm).then(resp => {
            this.$router.push('/board/index')
          })
        } else this.$message.error('缺少必要信息')
      }
    },
    handleQuotaChange(val) {
      this.indexList = ''
      this.deviceOptions = []
      this.deviceLoading = true
      const opt = this.quotaOptions[val]
      this.boardForm.quotaName = opt.name
      this.boardForm.unit = opt.unit
      const data = { quotaName: opt.name, unit: opt.unit, ...this.quotaForm }
      this.disableDevice = this.deviceLoading = true
      getDeviceByQuota(data).then(resp => {
        const items = resp.data.page.items
        for (const item of items) {
          this.deviceOptions.push({
            value: items.indexOf(item),
            label: item.number,
            device: item
          })
        }
        this.disableDevice = this.deviceLoading = false
      })
    },
    handleDeviceChange(val) {
      console.log('deviceVal', val, this.boardForm)
      const ls = []
      for (const idx of this.indexList) ls.push(this.deviceOptions[idx].device.id)
      this.boardForm.deviceIdList = ls.join(',')
      const end = Date.now()
      const beg = end - 1000 * 3600 * 24 * 7
      if (this.boardForm.deviceIdList.length) {
        const data = {
          quotaName: this.boardForm.quotaName,
          unit: this.boardForm.unit,
          deviceIdList: this.boardForm.deviceIdList,
          beg: parseTime(beg),
          end: parseTime(end),
          type: 3
        }
        previewBoard(data).then(resp => {
          const xData = resp.data.preview.xdata
          const series = resp.data.preview.series
          const unit = resp.data.preview.unit
          this.$refs.lineChart.updateOptions(xData, series, unit)
        })
      } else this.$refs.lineChart.updateOptions([], [], '')
    }
  }
}
</script>

<style lang="scss" scoped>

.board-container {
  padding: 20px;
  .chart-wrapper{
    margin-top: 40px;
  }
}

</style>
